package com.example.im.distribute

import android.text.TextUtils
import cc.vv.lkbasecomponent.util.LKJsonUtil
import cc.vv.lkimcomponent.lkim.bean.LKIMMessage
import cc.vv.lkimcomponent.lkim.bean.body.LKIMCmdBody
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMChatType
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMDirect
import cc.vv.lkimcomponent.lkim.operate.LKIMEdit
import cc.vv.lkimcomponent.lkim.operate.LKIMGet
import com.example.BaseNewApplication
import com.example.baselibrary.bean.UserManager
import com.example.baselibrary.db.dao.AccountDao
import com.example.baselibrary.db.dao.GroupDao
import com.example.baselibrary.db.table.AccountTable
import com.example.baselibrary.db.table.GroupTable
import com.example.im.IMInsert
import com.example.im.IMReceiveService
import com.example.im.bean.IMCmdAction
import com.example.util.finallist.IMExtKey
import com.example.util.finallist.SkKey

/**
 * 透传消息分发
 * @author  chaohaipeng  on 2018/7/23.
 */
class CMDMessageDistribute {

    private object mHolder {
        val instance = CMDMessageDistribute()
    }
    companion object {
        fun getInstance(): CMDMessageDistribute {
            return mHolder.instance
        }
    }
    /**
     * 消息分类处理
     *
     * @param lkimMessages 消息体集合
     */
    fun distribute(lkimMessages: List<LKIMMessage>) {
        for (lkimMessage in lkimMessages) {
            val lkimCmdBody = lkimMessage.lkIMBody as LKIMCmdBody
            val imCmdAction = LKJsonUtil.parseJsonToBean<IMCmdAction>(lkimCmdBody.action, IMCmdAction::class.java)
            val messageType = Integer.valueOf(imCmdAction.messageType)
            when (messageType) {
                SkKey.BTKEY_INT_1 -> repealCMD(lkimMessage, imCmdAction)
                SkKey.BTKEY_INT_4 -> ackCMD(lkimMessage, imCmdAction)
                SkKey.BTKEY_INT_5 -> groupChangeCMD(lkimMessage, imCmdAction)
            }
        }
    }

    /**
     * 撤销类型
     *
     * @param lkimMessage 消息体
     * @param imCmdAction action
     */
    private fun repealCMD(lkimMessage: LKIMMessage, imCmdAction: IMCmdAction) {
        try {
            val conversationId = imCmdAction.conversationId
            val messageId = imCmdAction.messageId
            if (!TextUtils.isEmpty(conversationId)) {
                if (conversationId!=null&&messageId!=null){
                    LKIMEdit.getInstance().delete(conversationId,messageId)
                    val nick =  imCmdAction.nick
                    val informIMMessage = IMInsert.getInstance().insertInformMessage(conversationId, String.format("%s 撤回了一条消息", nick), lkimMessage.msgTime, lkimMessage.lkimChatType)
                    BaseNewApplication.getInstance()?.mHandler?.postDelayed(Runnable { IMReceiveService.getInstance().sendInsertRepeal(conversationId,messageId, informIMMessage) }, 300)
                }


            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }


    /**
     * 消息已读类型
     *
     * @param lkimMessage 消息体
     * @param imCmdAction action
     */
    private fun ackCMD(lkimMessage: LKIMMessage, imCmdAction: IMCmdAction) {
        try {
            if (!TextUtils.isEmpty(imCmdAction.conversationId)) {
                val conversationId = imCmdAction.conversationId
                val messageId = imCmdAction.messageId
                if (conversationId!=null&&messageId!=null){
                    val dbIMMessage = LKIMGet.getInstance().getIMMessage(conversationId, messageId)
                    if (null != dbIMMessage && LKIMDirect.SEND == dbIMMessage.lkimDirect) {
                        dbIMMessage.setAttribute(IMExtKey.EXTKEY_ACKTIME, System.currentTimeMillis().toString())
                        val readMemberScount = dbIMMessage.getAttribute(IMExtKey.EXTKEY_READMEMBERSCOUNT, SkKey.BTKEY_String_0)
                        dbIMMessage.setAttribute(IMExtKey.EXTKEY_READMEMBERSCOUNT, (Integer.valueOf(readMemberScount)!! + 1).toString())
//                        if (conversationId.startsWith(SkKey.BTKEY_SECURITY_TAG) && LKIMStatus.SUCCESS != dbIMMessage.lkimStatus) {
//                            dbIMMessage.setLKIMStatus(LKIMStatus.SUCCESS)
//                        }
                        /*群组消息发送的已读回执,处理已读和未读成员id*/
                        if (TextUtils.equals(SkKey.BTKEY_String_1, imCmdAction.conversationType)) {
                            var unReadMemberIds = dbIMMessage.getAttribute(IMExtKey.EXTKEY_UNREADMEMBERIDS, "")
                            var readMemberIds = dbIMMessage.getAttribute(IMExtKey.EXTKEY_READMEMBERIDS, "")
                            val userId1 = imCmdAction.userId
                            if (userId1!=null){
                                if (!TextUtils.isEmpty(unReadMemberIds)) {
                                    if (unReadMemberIds.contains(String.format("%s,",userId1))) {
                                        unReadMemberIds = unReadMemberIds.replace(String.format("%s,", userId1), "")
                                    } else if (unReadMemberIds.contains(userId1)) {
                                        unReadMemberIds = unReadMemberIds.replace(userId1, "")
                                    }
                                }
                            }

                            dbIMMessage.setAttribute(IMExtKey.EXTKEY_UNREADMEMBERIDS, unReadMemberIds)
                            if (readMemberIds==null) {
                                val userId = imCmdAction?.userId
                                if (userId!=null){
                                    readMemberIds =userId
                                }
                            } else if (readMemberIds.endsWith(",")) {
                                readMemberIds = String.format("%s%s", readMemberIds, imCmdAction.userId)
                            } else {
                                readMemberIds = String.format("%s,%s", readMemberIds, imCmdAction.userId)
                            }
                            dbIMMessage.setAttribute(IMExtKey.EXTKEY_READMEMBERIDS, readMemberIds)
                        }
                        val conversationId = imCmdAction.conversationId
                        val messageId = imCmdAction.messageId
                        if (conversationId!=null&&messageId!=null){
                            LKIMEdit.getInstance().update(conversationId, dbIMMessage)
                            IMReceiveService.getInstance().sendRefreshMessage(conversationId,messageId, dbIMMessage)
                        }
                    }
                }
                }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    /**
     * 群组变动类型
     *
     * @param lkimMessage 消息体
     * @param imCmdAction action
     */
    private fun groupChangeCMD(lkimMessage: LKIMMessage, imCmdAction: IMCmdAction) {
        try {
            if (!TextUtils.isEmpty(imCmdAction.conversationId)) {
                val toUserIds = imCmdAction.toUserIds

                if (TextUtils.isEmpty(imCmdAction.toUserIds) || toUserIds!!.contains(UserManager.userId)) {
                    if (!TextUtils.isEmpty(imCmdAction.tipMessage)) {
                        val accountTable = AccountTable(imCmdAction.userId, imCmdAction.nick, imCmdAction.avatar)
                        AccountDao.getInstance().createOrUpdate(accountTable)
                        val groupTable = GroupTable(imCmdAction.groupId, imCmdAction.groupNick, imCmdAction.groupAvatar)
                        GroupDao.getInstance().updateGroup(groupTable)
                        val groupId = imCmdAction.groupId
                        val conversationId = imCmdAction.conversationId
                        val tipMessage = imCmdAction.tipMessage
                        if (tipMessage!=null&&conversationId!=null){
                            val informIMMessage = IMInsert.getInstance().insertInformMessage(conversationId, tipMessage, lkimMessage.msgTime, LKIMChatType.GroupChat)
                            BaseNewApplication.getInstance()?.mHandler?.postDelayed(object :Runnable{
                                override fun run() {
                                    if (groupId!=null){
                                        IMReceiveService.getInstance().sendInsertCache(groupId, informIMMessage, false)
                                        IMReceiveService.getInstance().sendRefreshConversation()
                                    }
                                }
                            },300)
                        }
                    }
                    val groupId = imCmdAction.groupId
                    if (groupId!=null){
                        /*刷新群组信息*/
                        IMReceiveService.getInstance().sendRefreshGroupInfo(groupId)
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    /**
     * 音视频透传消息
     *
     * @param lkimMessage 消息
     * @param imCmdAction action 数据实体类
     */
    private fun voipCMD(lkimMessage: LKIMMessage, imCmdAction: IMCmdAction) {
    }
}